package cn.itsource.smartcampus.interceptor;

import cn.itsource.smartcampus.util.TokenMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("进入到了拦截器中");
        // 1.告诉前端我响应的是一个JSON
        response.setContentType("application/json;charset=UTF-8");
        //从本地储存对象中获取到token之
        String token = request.getHeader("access-token");
        String parameter_token = request.getParameter("access-token");
        String type = request.getParameter("type");
        //字符串的工具类 判断是否为空
        if(StringUtils.isNotBlank(parameter_token)
                && StringUtils.isNotBlank(type)
                && TokenMap.getTokenMap(parameter_token)!= null){
                return  true;
        }else if(StringUtils.isBlank(parameter_token)&& StringUtils.isNotBlank(type)){
            //PrintWriter writer = response.getWriter();
            //writer.write("{\"code\":\"401\"}");
            response.sendRedirect("http://localhost:63342/Day45_smart_campus_view/pages/login/login.html");
            return false; // 拦截
        }
        Object o = TokenMap.getTokenMap(token);
        if ("".equals(o) || null == o){
            // 2.设置响应数据
            PrintWriter writer = response.getWriter();
            writer.write("{\"code\":\"401\"}");
            return false; // 拦截
        }
        //登录成功了 直接放行
        return true;
    }
}
